//
//  KeChengSCViewController.m
//  ZhiBoYuan
//
//  Created by coder_di on 2018/5/17.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "KeChengSCViewController.h"

#import "ShouCangTableViewCell.h"
#import "AdetailViewController.h"

@interface KeChengSCViewController ()<UITableViewDelegate,UITableViewDataSource>

//@property (nonatomic, strong)UITableView *tableView;

@property(nonatomic,strong)AxcEmptyDataTableView *tableView;

@property (nonatomic, strong)NSMutableArray *dataArray;

@property (nonatomic, assign)int pageIndex;

@end

@implementation KeChengSCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
        _dataArray = [[NSMutableArray alloc] init];
        _pageIndex = 1;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
        [self loadData];
    
        [self addTableView];
    
        [self.tableView registerClass:[ShouCangTableViewCell class] forCellReuseIdentifier:@"ShouCangTableViewCell"];
    
}


-(void)loadData{
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{@"page":[NSString stringWithFormat:@"%d",_pageIndex],
                       @"page_count":@"10"
                       };
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Collect&a=courseList",HTTPP] parameter:parameter sucess:^(id responseObject) {
        
        if (_pageIndex == 1) {
            [_dataArray removeAllObjects];
        }
        NSLog(@"%@",responseObject);
        
        NSDictionary *dic = responseObject;
        
        if ([dic[@"status"] intValue] == 200) {
            for (NSDictionary *dicc in dic[@"data"][@"course_list"]) {
                [_dataArray addObject:dicc];
            }
            
            if (_dataArray.count < 4) {
                _tableView.mj_footer.hidden = YES;
            }else{
                _tableView.mj_footer.hidden = NO;
            }
            
            [self.tableView reloadData];
            
        }else{
            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}

-(void)addTableView {
    _tableView = [[AxcEmptyDataTableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT -TAB_BAR_HEIGHT) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    _tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
    
    _tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
    
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    //        self.extendedLayoutIncludesOpaqueBars = YES;
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    if (iPhoneX) {
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.scrollIndicatorInsets = _tableView.contentInset;
    }
        
    [_tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    
    // 下拉刷新
    _tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.pageIndex = 1;
        
        [self loadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [_tableView.mj_header endRefreshing];
        });
    }];
    
    //         上拉加载
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        _pageIndex = _pageIndex + 1;
        [self loadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_tableView.mj_footer endRefreshing];
            
        });
    }];
    
    
    
    self.placeholderView.frame = _tableView.bounds;
    
    // 设置空集时候展示的View
    _tableView.axcUI_placeHolderView = self.placeholderView;
    
    //  默认YES 自带渐入渐出动画效果，下边这个参数可以关闭
    _tableView.axcUI_placeHolderViewAnimations = NO;
    
    // 占位View的“重新加载”按钮的Block回调:
    __weak typeof(self) WeakSelf = self;
    
    self.placeholderView.clickLoadBtnBlock = ^(id type) {
        //        WeakSelf.dataArray = nil;
        self.pageIndex = 1;
        
        [self loadData];
        
        
    };[self.view addSubview:_tableView];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation
//-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return 1;
//}


-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{
    
    return 0;
    
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifity = @"MyKeCHengTableViewCell";
    //    MyIndentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifity];
    ShouCangTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[ShouCangTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifity];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    cell.nameLable.text = [_dataArray[indexPath.row] valueForKey:@"name"];
    [cell.imageVC sd_setImageWithURL:[NSURL URLWithString:[_dataArray[indexPath.row] valueForKey:@"image_url"]] placeholderImage:[UIImage imageNamed:@"0009"]];
    
    
    cell.guanZhuBtn.tag = 1000 + indexPath.row;
    [cell.guanZhuBtn addTarget:self action:@selector(quxiaoGZAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    return cell;
}

//取消收藏
- (void)quxiaoGZAction:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    int selectTag = (int)btn.tag;
    int row = selectTag - 1000;
    NSLog(@"%d",row);
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{@"course_id":[_dataArray[row] valueForKey:@"id"],
                       };
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Collect&a=delCourse",HTTPP] parameter:parameter sucess:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject;
        
        if ([dic[@"status"] intValue] == 200) {
            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
            [_dataArray removeObjectAtIndex:row];
            
            
            [self.tableView reloadData];
            
            //            [self loadData];
            
        }else{
            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 120 * KscreenHeight;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //    AdetailViewController *adetailVC =  [[AdetailViewController alloc]init];
    //    adetailVC.course_id = [_dataArray[indexPath.row] valueForKey:@"id"];
    //    [self.navigationController pushViewController:adetailVC animated:YES];
    
    [Helper keChengDetailFromVC:ZYCurrentViewController() course_id:[_dataArray[indexPath.row] valueForKey:@"id"]];
    
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
